const express = require('express');
const router = express.Router();
const exporting = require("node-highcharts-exporting");
const Utils = require("../util/Utils");
const RedisUtil = require("../util/RedisUtil");
const CacheKeyUtil = require("../util/CacheKeyUtil");
const DateUtil = require("../util/DateUtil");

router.get('/:owner/:repo', async function (req, res, next) {
    await renderImg(req, res)
});

async function renderImg(req, res) {
    // 仓库所有者
    const owner = req.params.owner
    // 仓库名
    const repo = req.params.repo

    if (!owner || !repo) {
        console.log("owner 或者 repo 不全")
        return;
    }
    // 数据过期时间，不填时默认取 {@code config.redis.expire}
    let expire = Utils.getRealExpireTime(req.query.e)

    const repoKey = CacheKeyUtil.repoKey(owner, repo)
    const precessKey = CacheKeyUtil.precessKey(repoKey)
    const projectUsageTimeKey = CacheKeyUtil.trendKey.usageTime(owner, repo)
    const projectStarTimeKey = CacheKeyUtil.trendKey.startTime(owner, repo)
    await Utils.getStarChartData(owner, repo, 1, {}, async function (data) {
        console.log("获取完毕", repoKey, "的 star 数据，标记当前任务状态为结束...")

        // 标记线程结束，情况状态缓存
        await RedisUtil.del(precessKey)

        // 获取加载图表程序的开始时间
        const projectStartTime = parseInt(await RedisUtil.get(projectStarTimeKey))
        // 结束的时间
        const projectEndTime = new Date().getTime()
        await RedisUtil.del(projectStarTimeKey)
        // 计算耗时，单位毫秒
        const projectUsageTime = projectEndTime - projectStartTime;
        const itemObj = {
            startTime: projectStartTime,
            endTime: projectEndTime,
            usageTime: projectUsageTime,
        }
        await RedisUtil.sadd(projectUsageTimeKey, itemObj)

        const starInfo = data.starInfo

        let xAxisData = starInfo.dateList;
        let seriesData = starInfo.data;

        const xStep = parseInt((seriesData.length / 5).toFixed(0))
        const yStep = parseInt((seriesData.length / 5).toFixed(0))
        const options = {
            width: 900,
            data: {
                chart: {
                    height: 200
                },
                title: {
                    text: null
                },
                legend: {
                    enabled: false
                },
                credits: {
                    enabled: false
                },
                xAxis: {
                    categories: xAxisData,
                    tickInterval: xStep,
                    tickmarkPlacement: 'on',
                    tickLength: 5,
                    labels: {
                        style: {
                            color: 'gray',
                            fontSize: '8px'
                        }
                    }
                },
                yAxis: {
                    title: {
                        text: 'Gitee Repo Stargazers'
                    },
                    gridLineDashStyle: 'longdash',
                    // lineWidth: 1,
                    gridLineWidth: 0.2,
                    min: 0,
                    opposite: true,
                    tickInterval: yStep,
                    tickmarkPlacement: 'on',
                    labels: {
                        style: {
                            color: 'gray',
                            fontSize: '8px'
                        },
                        align: 'left',
                    }
                },
                series: [{
                    type: "line",
                    lineWidth: 1,
                    marker: {
                        enabled: false
                    },
                    data: seriesData
                }]
            },
        };
        exporting(options, function (err, data) {
            Utils.saveImgAndWriteToResponse(data, res);
        })
    }, expire)
}

module.exports = router;
